import React, { useState, useEffect } from "react";
import MemeCanvas from "./components/MemeCanvas";
import ControlsPanel from "./components/ControlsPanel";
import TemplateModal from "./components/TemplateModal";
import PhraseList from "./components/PhraseList";
import {
  fetchTemplates,
  fetchPopularMemes,
  generateMeme,
  checkHealth,
} from "./services/api";
import "./App.css";

function App() {
  const [image, setImage] = useState(null);
  const [textElements, setTextElements] = useState([]);
  const [selectedTextId, setSelectedTextId] = useState(null);
  const [font, setFont] = useState("Impact");
  const [color, setColor] = useState("#ffffff");
  const [size, setSize] = useState(40);
  const [stickers, setStickers] = useState([]);
  const [filter, setFilter] = useState("none");
  const [showTemplateModal, setShowTemplateModal] = useState(false);
  const [templates, setTemplates] = useState([]);
  const [popularMemes, setPopularMemes] = useState([]);
  const [generatingMeme, setGeneratingMeme] = useState(false);
  const [backendStatus, setBackendStatus] = useState({
    status: "检查中...",
    connected: false,
  });
  const [nextId, setNextId] = useState(1);

  const selectedText = textElements.find((elem) => elem.id === selectedTextId);

  // 默认文字样式
  const defaultTextStyle = {
    font: "Impact",
    color: "#FFFFFF",
    size: 40,
    strokeColor: "#000000",
    strokeWidth: 3,
    bold: true,
    italic: false,
    shadow: false,
    shadowColor: "#000000",
    shadowBlur: 3,
    shadowOffsetX: 2,
    shadowOffsetY: 2,
    align: "center",
    verticalPosition: "default",
    animation: "bounce",
  };

  // 处理文字样式变更
  const handleTextStyleChange = (property, value) => {
    if (!selectedTextId) return;

    setTextElements((prevElements) =>
      prevElements.map((elem) =>
        elem.id === selectedTextId
          ? {
              ...elem,
              style: {
                ...elem.style,
                [property]: value,
              },
            }
          : elem
      )
    );
  };

  // 处理文字动画变更
  const handleTextAnimationChange = (textId, animation) => {
    if (!textId) return;

    setTextElements((prevElements) =>
      prevElements.map((elem) =>
        elem.id === textId
          ? {
              ...elem,
              style: {
                ...elem.style,
                animation: animation,
              },
            }
          : elem
      )
    );
  };

  useEffect(() => {
    const checkBackendStatus = async () => {
      try {
        const health = await checkHealth();
        setBackendStatus({
          status: `已连接: ${health.message}`,
          connected: true,
        });
      } catch (error) {
        setBackendStatus({
          status: "未连接: 后端服务不可用",
          connected: false,
        });
      }
    };

    checkBackendStatus();

    const loadData = async () => {
      try {
        const [templatesData, popularData] = await Promise.all([
          fetchTemplates(),
          fetchPopularMemes(),
        ]);
        setTemplates(templatesData);
        setPopularMemes(
          popularData
            .map((meme) => meme.topText || meme.bottomText)
            .filter(Boolean)
        );
      } catch (error) {
        console.error("加载数据失败:", error);
      }
    };

    if (backendStatus.connected) {
      loadData();
    }
  }, [backendStatus.connected]);

  const handleImageUpload = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        const img = new Image();
        img.onload = () => setImage(img);
        img.src = event.target.result;
      };
      reader.readAsDataURL(file);
    }
  };

  const handleTemplateSelect = (template) => {
    const img = new Image();
    img.onload = () => {
      setImage(img);
      setShowTemplateModal(false);
    };
    img.src = template.imageUrl || `http://localhost:8080${template.filePath}`;
  };

  const handleAddSticker = (emoji) => {
    const newSticker = {
      emoji,
      x: Math.random() * 400 + 50,
      y: Math.random() * 400 + 50,
      size: Math.random() * 30 + 30,
      rotation: 0,
    };
    setStickers([...stickers, newSticker]);
  };

  const handleStickerDrag = (index, x, y) => {
    setStickers((prevStickers) =>
      prevStickers.map((sticker, i) =>
        i === index ? { ...sticker, x, y } : sticker
      )
    );
  };

  const handleStickerSizeChange = (index, size) => {
    setStickers((prevStickers) =>
      prevStickers.map((sticker, i) =>
        i === index ? { ...sticker, size } : sticker
      )
    );
  };

  const handleStickerRotationChange = (index, rotation) => {
    setStickers((prevStickers) =>
      prevStickers.map((sticker, i) =>
        i === index ? { ...sticker, rotation } : sticker
      )
    );
  };

  const handleCanvasClick = (e) => {
    if (!image) return;

    const canvas = e.target;
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    setStickers(
      stickers.filter((sticker) => {
        const distance = Math.sqrt(
          Math.pow(x - sticker.x, 2) + Math.pow(y - sticker.y, 2)
        );
        return distance > 30;
      })
    );
  };

  const handleTextContentChange = (textId, newContent) => {
    setTextElements((elements) =>
      elements.map((elem) =>
        elem.id === textId ? { ...elem, text: newContent } : elem
      )
    );
  };

  const handleAddText = (x, y) => {
    if (!image) return;

    // 获取画布元素（添加随机偏移使文本不重叠）
    const canvas = document.querySelector(".meme-canvas");
    if (!canvas) return;

    // 使用画布宽高的中心位置
    const canvasWidth = canvas.width || 600;
    const canvasHeight = canvas.height || 400;

    // 添加一个小的随机偏移，避免多个文本完全重叠
    const offsetX = Math.floor(Math.random() * 60) - 30; // -30 到 30 之间的随机偏移
    const offsetY = Math.floor(Math.random() * 60) - 30; // -30 到 30 之间的随机偏移

    // 基于画布中心位置
    const posX = canvasWidth / 2 + offsetX;
    const posY = canvasHeight / 2 + offsetY;

    // 创建新文本对象
    const newText = {
      id: nextId,
      text: "新文本",
      x: posX,
      y: posY,
      isTop: false,
      style: { ...defaultTextStyle },
    };

    setTextElements((prev) => [...prev, newText]);
    setSelectedTextId(newText.id);
    setNextId((prev) => prev + 1);
  };

  const handleDeleteText = (textId) => {
    setTextElements((elements) =>
      elements.filter((elem) => elem.id !== textId)
    );
    if (selectedTextId === textId) {
      setSelectedTextId(null);
    }
  };

  const handleSelectText = (textId) => {
    setSelectedTextId(textId);
  };

  const handleTextDrag = (textId, newX, newY) => {
    setTextElements((elements) =>
      elements.map((elem) =>
        elem.id === textId ? { ...elem, x: newX, y: newY } : elem
      )
    );
  };

  const handleMemeGenerate = async (canvas) => {
    if (!image || !backendStatus.connected) return;

    setGeneratingMeme(true);
    try {
      const blob = await new Promise((resolve) => {
        canvas.toBlob(resolve, "image/png");
      });

      const formData = new FormData();
      formData.append("image", blob, "meme.png");

      const topText = textElements.find((elem) => elem.isTop)?.text || "";
      const bottomText = textElements.find((elem) => !elem.isTop)?.text || "";

      formData.append("topText", topText);
      formData.append("bottomText", bottomText);

      const result = await generateMeme(formData);
      console.log("Meme created:", result);
      alert("表情包已保存到服务器！");
    } catch (error) {
      console.error("生成表情包失败:", error);
      alert("生成表情包失败：" + (error.message || "未知错误"));
    } finally {
      setGeneratingMeme(false);
    }
  };

  const handlePhraseSelect = (phrase) => {
    if (!image) return; // 如果没有图片，不执行任何操作

    // 获取画布元素
    const canvas = document.querySelector(".meme-canvas");
    if (!canvas) return;

    // 使用画布宽高的中心位置
    const canvasWidth = canvas.width || 600;
    const canvasHeight = canvas.height || 400;

    // 添加一个小的随机偏移，避免多个文本完全重叠
    const offsetX = Math.floor(Math.random() * 60) - 30; // -30 到 30 之间的随机偏移
    const offsetY = Math.floor(Math.random() * 60) - 30; // -30 到 30 之间的随机偏移

    // 基于画布中心位置
    const posX = canvasWidth / 2 + offsetX;
    const posY = canvasHeight / 2 + offsetY;

    // 创建新文本对象
    const newText = {
      id: nextId,
      text: phrase,
      x: posX,
      y: posY,
      isTop: false,
      style: { ...defaultTextStyle },
    };

    setTextElements((prev) => [...prev, newText]);
    setSelectedTextId(newText.id);
    setNextId((prev) => prev + 1);
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>表情包生成器</h1>
        <div
          className={`backend-status ${
            backendStatus.connected ? "connected" : "disconnected"
          }`}
        >
          {backendStatus.status}
        </div>
      </header>

      <main className="app-main">
        <div className="editor-container">
          <div className="meme-canvas-container">
            <MemeCanvas
              image={image}
              textElements={textElements}
              selectedTextId={selectedTextId}
              stickers={stickers}
              filter={filter}
              onCanvasClick={handleCanvasClick}
              onTextDrag={handleTextDrag}
              onStickerDrag={handleStickerDrag}
              onStickerSizeChange={handleStickerSizeChange}
              onStickerRotationChange={handleStickerRotationChange}
              onSelectText={handleSelectText}
              onAddText={handleAddText}
              onDeleteText={handleDeleteText}
              font={font}
              color={color}
              size={size}
              onGenerate={handleMemeGenerate}
              generating={generatingMeme}
            />
            {generatingMeme && <div className="loading">生成中...</div>}
          </div>

          <div className="controls-panel">
            <ControlsPanel
              onImageUpload={handleImageUpload}
              onUseTemplate={() => setShowTemplateModal(true)}
              font={font}
              onFontChange={setFont}
              color={color}
              onColorChange={setColor}
              size={size}
              onSizeChange={setSize}
              onFilterChange={setFilter}
              onAddSticker={handleAddSticker}
              selectedText={selectedText}
              onTextContentChange={handleTextContentChange}
              onTextStyleChange={handleTextStyleChange}
              onTextAnimationChange={handleTextAnimationChange}
              textElements={textElements}
              onAddText={handleAddText}
              onDeleteText={handleDeleteText}
              onSelectText={handleSelectText}
            />
          </div>
        </div>

        <PhraseList
          phrases={popularMemes}
          onPhraseSelect={handlePhraseSelect}
        />
      </main>

      {showTemplateModal && (
        <TemplateModal
          templates={templates}
          onClose={() => setShowTemplateModal(false)}
          onSelect={handleTemplateSelect}
        />
      )}
    </div>
  );
}

export default App;
